#include "StdAfx.h"
#include "StringFinder.h"
#include "PyFinder.h"


struct ChsCharTraits : public std::char_traits<wchar_t>
{
	static wchar_t ToLower(wchar_t c)
	{
		return (c >= 'A' && c <= 'Z') ? c - 'A' + 'a' : c;
		
	}
	static bool __CLRCALL_OR_CDECL eq(const wchar_t& _Left, const wchar_t& _Right)
	{	// test for element equality
		if (ToLower(_Left) == ToLower(_Right))
		{
			return true;
		}
		
		std::wstring ls = PyFinder::Instance().GetShengmu(_Left);
		std::wstring rs = PyFinder::Instance().GetShengmu(_Right);
		if ( ls.empty() == rs.empty())
		{
			return false;
		}
		if (ls.empty())
		{
			return rs.find(_Left) != std::wstring::npos;
		}
		else
		{
			return ls.find(_Right) != std::wstring::npos;
		}
	}
	static const wchar_t * wmemchr(const wchar_t *_S, const wchar_t _C, _In_ size_t _N)
	{
		for (; 0 < _N; ++_S, --_N)
			if (eq(*_S, _C))
				return (_CONST_RETURN wchar_t *)(_S);
		return (0); 
	}

	static __inline int __CRTDECL wmemcmp(_In_count_(_N) const wchar_t *_S1, _In_count_(_N) const wchar_t *_S2, _In_ size_t _N)
	{for (; 0 < _N; ++_S1, ++_S2, --_N)
	if (!eq(*_S1, *_S2))
		return (*_S1 < *_S2 ? -1 : +1);
	return (0); }

	static const _Elem *__CLRCALL_OR_CDECL find(const _Elem *_First, size_t _Count,
		const _Elem& _Ch)
	{	// look for _Ch in [_First, _First + _Count)
		//		_DEBUG_POINTER(_First);
		return ((const _Elem *)wmemchr(_First, _Ch, _Count));
	}


	static int __CLRCALL_OR_CDECL compare(const _Elem *_First1, const _Elem *_First2,
		size_t _Count)
	{	// compare [_First1, _First1 + _Count) with [_First2, ...)
		//		_DEBUG_POINTER(_First1);
		//		_DEBUG_POINTER(_First2);
		return (wmemcmp(_First1, _First2, _Count));
	}

};

struct ChsString : public std::basic_string<wchar_t, ChsCharTraits, std::allocator<wchar_t> > 
{
	void Copy(const std::wstring& ss)
	{
		this->resize(ss.length());
		ss.copy(this->_Myptr(), ss.length());
		
	}
};

StringFinder::StringFinder(void)
{
	//mPyFinder->Init();
}

StringFinder::~StringFinder(void)
{
}

bool StringFinder::Find( const std::wstring& shortStr, const std::wstring longStr, int* found)
{
	ChsString s, l;
	s.Copy(shortStr);
	l.Copy(longStr);
	int f = l.find(s);
	if (found)
	{	
		*found = f;
	}
	return f != ChsString::npos;
	
}

void StringFinder::Init(char* pData, int size)
{
	PyFinder::Instance().Init(pData, size);
}